<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\ocean;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\enum\OeInvalidVideoEnum;
use app\model\ClientAccountModel;
use app\model\mysql\OeRebateMaterialModel;
use app\model\OeInvalidVideoModel;
use app\model\OeInvalidVideoRecordModel;
use app\service\BaseService;
use app\service\client\AccountService;
use think\facade\Db;

class VideoService extends BaseService
{
    /**
     * 关停无效素材.
     *
     * @param OeRebateMaterialModel $model 无效素材表模型
     */
    public static function VideoPause(OeRebateMaterialModel $model): bool
    {
        if (! $model->getKey()) {
            return self::setError('获取无效素材模型失败');
        }

        if ($model->getAttr('status') == OeRebateMaterialModel::STATUS_STOP_YES) {
            return true;
        }

        $advertiserId = $model->getAttr('advertiser_id');

        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'material_ids' => $model->getAttr('material_id'),
        ];

        if (! MaterialService::setVideoPause($headers, $params)) {
            $model->setAttr('status', OeRebateMaterialModel::STATUS_STOP_OK);
            if (! $model->save()) {
                return self::setError('设置素材关停状态失败');
            }
            return true;
        }
        return false;
    }

    public static function getInvalidVideo(string $agentId = '', string $month = '', array $filtering = []): bool
    {
        $record = (new OeInvalidVideoRecordModel())->where('agent_id', $agentId)->field(true)->find();
        if ($record instanceof OeInvalidVideoRecordModel && $record->getKey() && $record->getAttr('status') == '0') {
            return self::setError('无效素材拉取中');
        }
        if (! $record instanceof OeInvalidVideoRecordModel || ! $record->getKey()) {
            $record = new OeInvalidVideoRecordModel();
        }
        $advertiserId = (new ClientAccountModel())->where('media_id', CommonEnum::OE_MEDIA)
            ->where('agent_advertiser_id', '1689736213017623')->where('auth_valid', 1)->value('advertiser_id');
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'agent_id' => $agentId,
            'period' => $month,
            'page_size' => OceanEnum::MAX_PAGE_FIVE_SIZE,
        ];
        if (! empty($filtering)) {
            $params['filtering'] = $filtering;
        }
        Db::startTrans();
        try {
            $record->setAttrs([
                'agent_id' => $agentId,
                'status' => 0,
            ]);
            if (! $record->save()) {
                throw new \Exception('更新拉取开始时的状态失败');
            }

            // 删除未处理的记录
            (new OeInvalidVideoModel())->where(['agent_id' => $agentId, 'data_ym' => date('Ym'), 'close_status' => OeInvalidVideoEnum::CLOSE_STATUS_START])->delete();

            $page = 1;
            while (true) {
                $params['page'] = $page;
                $result = AdvertiserService::getRebateMaterialList($headers, $params);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['materials']) == 0) {
                    break;
                }
                foreach ($result['data']['materials'] as $material) {
                    $model = (new OeInvalidVideoModel())->where([
                        'advertiser_id' => $material['advertiser_id'],
                        'material_id' => $material['material_info']['material_id'],
                        'data_ym' => date('Ym', strtotime($month)),
                    ])->field(true)->find();
                    if (! $model instanceof OeInvalidVideoModel || ! $model->getKey()) {
                        $model = new OeInvalidVideoModel();
                    }

                    $data = [
                        'agent_id' => $agentId,
                        'advertiser_id' => $material['advertiser_id'],
                        'operator_tag' => $material['operator_tag'],
                        'rebate_calc_policy_type' => $material['rebate_calc_policy_type'],
                        'rebate_calc_settlement_stats_type' => $material['rebate_calc_settlement_stats_type'],
                        'rebate_calc_first_industry_name' => $material['rebate_calc_first_industry_name'] ?? '',
                        'rebate_calc_second_industry_name' => $material['rebate_calc_second_industry_name'] ?? '',
                        'customer_name' => $material['customer_name'],
                        'optimizer_name' => $material['optimizer_name'],
                        'agent_sale_name' => $material['agent_sale_name'] ?? '',
                        'second_ad_agent_id' => $material['second_ad_agent_id'],
                        'material_id' => $material['material_info']['material_id'],
                        'material_is_effective' => $material['material_info']['material_is_effective'],
                        'is_valid_video_material' => $material['material_info']['is_valid_video_material'],
                        'policy_cost' => $material['material_info']['policy_cost'],
                        'cost' => $material['material_info']['cost'],
                        'material_create_time' => strtotime($material['material_info']['material_create_time']),
                        'material_tags' => json_encode($material['material_info']['material_tags'], JSON_UNESCAPED_UNICODE),
                        'ad_ids' => json_encode($material['material_info']['ad_ids'], JSON_UNESCAPED_UNICODE),
                        'promotion_ids' => json_encode($material['material_info']['promotion_ids'], JSON_UNESCAPED_UNICODE),
                        'auto_ad_ids' => json_encode($material['material_info']['auto_ad_ids'], JSON_UNESCAPED_UNICODE),
                        'auto_promotion_ids' => json_encode($material['material_info']['auto_promotion_ids'], JSON_UNESCAPED_UNICODE),
                        'update_date' => $material['update_date'],
                        'data_ym' => date('Ym', strtotime($month)),
                        'close_status' => OeInvalidVideoEnum::CLOSE_STATUS_START,
                        // 如果没有自动化生成的广告，无需做定点清理
                        'step_adv_status' => empty($material['material_info']['auto_promotion_ids']) ? OeInvalidVideoEnum::CLOSE_STATUS_SUCCESS : OeInvalidVideoEnum::CLOSE_STATUS_START,
                    ];
                    $model->setAttrs($data);
                    if (! $model->save()) {
                        throw new \Exception('保存信息出错');
                    }
                }

                ++$page;
            }

            $record->setAttrs([
                'agent_id' => $agentId,
                'status' => 1,
            ]);
            if (! $record->save()) {
                throw new \Exception('更新拉取完毕后的状态失败');
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }
}
